package com.mck.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mck.service.AiReactiveService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AiReactiveServiceImpl implements AiReactiveService {

  @Value("${ai.model.api-key}")
  private String apiKey;

  @Value("${ai.model.base-url:https://api.deepseek.com}")
  private String baseUrl;

  private final WebClient webClient;
  private final ObjectMapper objectMapper;

  public AiReactiveServiceImpl() {
    this.webClient = WebClient.builder()
        .baseUrl(baseUrl)
        .build();
    this.objectMapper = new ObjectMapper();
  }

  @Override
  public Flux<String> processAiRequestReactive(String message) {
    // 准备消息
    List<Map<String, String>> messages = new ArrayList<>();

    // 系统消息
    Map<String, String> systemMessage = new HashMap<>();
    systemMessage.put("role", "system");
    systemMessage.put("content", "你是一个有帮助的AI助手。");
    messages.add(systemMessage);

    // 用户消息
    Map<String, String> userMessage = new HashMap<>();
    userMessage.put("role", "user");
    userMessage.put("content", message);
    messages.add(userMessage);

    // 准备请求体
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("model", "deepseek-chat");
    requestBody.put("messages", messages);
    requestBody.put("temperature", 0.7);
    requestBody.put("max_tokens", 2000);
    requestBody.put("stream", true);

    return webClient
        .post()
        .uri("/v1/chat/completions")
        .header("Authorization", "Bearer " + apiKey)
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(requestBody)
        .retrieve()
        .bodyToFlux(String.class)
        .map(line -> {
          try {
            if (line.startsWith("data: ")) {
              String data = line.substring(6);
              if ("[DONE]".equals(data)) {
                return "";
              }
              Map<String, Object> jsonData = objectMapper.readValue(data, Map.class);
              List<Map<String, Object>> choices = (List<Map<String, Object>>) jsonData.get("choices");
              if (!choices.isEmpty()) {
                Map<String, Object> choice = choices.get(0);
                Map<String, Object> delta = (Map<String, Object>) choice.get("delta");
                if (delta != null && delta.containsKey("content")) {
                  return (String) delta.get("content");
                }
              }
            }
            return "";
          } catch (Exception e) {
            return "";
          }
        })
        .filter(content -> !content.isEmpty());
  }
}